<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./v4.6.5-dist/ol.css">
    <title>geo</title>
    <script src="./v4.6.5-dist/ol.js"></script>
    <style>
        #main {
            width: 100%;
            height: 80%;
        }
    </style>
    <!--<script src="geoJson.js"></script>-->
    <script src="./geoJson.js"></script>
</head>
<body>
<div id="text"></div>
<div id="main">

</div>
<span>features个数</span>
<button onclick="hiling()">点击高亮</button>
<button onclick="diling()">点击高亮</button>
<button onclick="dell()">删除</button>
<script>
    var styleFunction = function () {
        return function (feature, resolution) {
            //点
            if (feature.getGeometry().getType() == 'Point') {
                var point = new ol.style.Style({
                    image: new ol.style.Circle({
                        radius: 5,
                        fill: new ol.style.Fill({
//                            color: feature.get("fillColor")
                            color: 'red'
                        }),
                        stroke: new ol.style.Stroke({
                            color: feature.get("borderColor"),
                            size: 1
                        })
                    })
                })
                return [point]
            }

            if (feature.getGeometry().getType() == 'MultiPoint') {
                var MultiPoint = new ol.style.Style({
                    image: new ol.style.Circle({
                        radius: 5,
                        fill: new ol.style.Fill({
//                            color: feature.get("fillColor")
                            color: '#000'
                        }),
                        stroke: new ol.style.Stroke({
                            color: feature.get("borderColor"),
                            size: 1
                        })
                    })
                })
                return [MultiPoint]
            }

            //面
            if (feature.getGeometry().getType() == 'MultiPolygon') {
                var MultiPolygon = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: feature.get('borderColor'),
                        width: feature.get("size")
                    }),
                    fill: new ol.style.Fill({
                        color: feature.get("fillColor")
                    }),
                    text: new ol.style.Text({
                        font: '12px Calibri,sans-serif',
                        text: feature.get('text'),
                        fill: new ol.style.Fill({
                            color: feature.get('color')
                        }),
                        stroke: new ol.style.Stroke({
                            color: 'white',
                            width: 2
                        })
                    })
                })
                return [MultiPolygon]
            }

            if (feature.getGeometry().getType() == 'Polygon') {
                var Polygon = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: feature.get('borderColor'),
                        width: feature.get("size")
                    }),
                    fill: new ol.style.Fill({
//                        color: feature.get("fillColor")
                        color: 'blue'
                    }),
                    text: new ol.style.Text({
                        font: '12px Calibri,sans-serif',
                        text: feature.get('text'),
                        fill: new ol.style.Fill({
                            color: feature.get('color')
                        }),
                        stroke: new ol.style.Stroke({
                            color: 'white',
                            width: 2
                        })
                    })
                })
                return [Polygon]
            }

            //线
            if (feature.getGeometry().getType() == 'LineString') {
                var LineString = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: feature.get('borderColor'),
                        width: 10
                    }),
                    image: new ol.style.Circle({
                        radius: 10,
                        fill: new ol.style.Fill({
                            color: feature.get('borderColor')
                        }),
                        stroke: new ol.style.Stroke({
                            color: 'blue'
                        })
                    }),
                })
                return [LineString]
            }

            if (feature.getGeometry().getType() == 'MultiLineString') {
                var MultiLineString = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: feature.get('borderColor'),
                        width: 2
                    }),
                    image: new ol.style.Circle({
                        radius: 10,
                        fill: new ol.style.Fill({
                            color: feature.get('borderColor')
                        }),
                        stroke: new ol.style.Stroke({
                            color: 'blue'
                        })
                    }),
                })
                return [MultiLineString]
            }

        }
    }
    var geojsonObject = {
        'type': 'FeatureCollection',
        'crs': {
            'type': 'name',
            'properties': {
                'name': 'EPSG:4326'
            }
        },
        'features': []
    };

    var vectorSource = new ol.source.Vector({
        features: (new ol.format.GeoJSON(
            {
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            }
        )).readFeatures(geojsonObject)
    });

    var vectorLayer = new ol.layer.Vector({
        source: vectorSource,
        style: styleFunction()
    });

    var basemap = new ol.layer.Tile({
        source: new ol.source.XYZ({
            url: "http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}"
        })
    })
    var map = new ol.Map({
        target: "main",
        layers: [basemap,
            vectorLayer
        ],
        view: new ol.View({
            center: ol.proj.transform([115.74848777200009, 40.513730578000036], 'EPSG:4326', 'EPSG:3857'),
            zoom: 11
        })
    })


    var sources = vectorLayer.getSource();

    CESHI.data.forEach((e => {
        sources.addFeatures(
            (new ol.format.GeoJSON({
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            })).readFeatures({
                "id": e.id,
                "properties": {
                    "name": e.name,
                    "borderColor": "#1FB456",
                    "fillColor": "yellow",
                    "size": 1,
                    "text": ""
                },
                'type': 'Feature',
                'geometry': e.geojson
            }))
    }))


    /*计算面积*/

    /* var featureArr = vectorSource.getFeatures(),
     sum = 0;
     for (var i = 0; i < featureArr.length; i++) {
     var polygon = featureArr[i].getGeometry();
     if(featureArr[i].getGeometry() instanceof ol.geom.Polygon || featureArr[i].getGeometry() instanceof ol.geom.MultiPolygon){
     var area = ol.Sphere.getArea(polygon);
     var output;
     if (area > 10000) {
     output = (Math.round(area / 1000000 * 100) / 100) ;
     } else {
     output = (Math.round(area * 100) / 100);
     }

     sum += output;
     }

     }
     console.log(sum);*/

    var thisfeature = vectorSource.getFeatureById("568");


    var center = thisfeature.getGeometry().getFirstCoordinate();

    /*var xy = ol.proj.transform(thisfeature.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326')

     console.log(xy);
     function convert(value) {
     ///<summary>将度转换成为度分秒</summary>
     if (value == 0) {
     return 0
     } else {
     var str1 = value.toString().split(".");
     var du1 = str1[0];
     var tp = "0." + str1[1]
     var tp = String(tp * 60);		//这里进行了强制类型转换
     var str2 = tp.split(".");
     var fen = str2[0];
     tp = "0." + str2[1];
     tp = tp * 60;
     var miao = tp.toFixed(2);
     if (du1 <= 0 || du1 == "NaN") {
     du1 = 0
     }
     if (fen <= 0 || du1 == "NaN") {
     fen = 0
     }
     if (miao <= 0 || miao == "NaN") {
     miao = 0
     }
     return du1 + '°' + fen + '\'' + miao + '"';
     }
     }

     console.log(convert(xy[0]));
     console.log(convert(xy[1]));*/

    function hiling() {
        map.getView().setCenter(center);
        map.getView().setZoom(10);//设置缩放级别
        thisfeature.set("size", 5);
        thisfeature.set("text", "点击设置样式");
        var geom = thisfeature.getGeometry();

        console.log(geom);

        if (geom instanceof ol.geom.Polygon || geom instanceof ol.geom.MultiPolygon) {
            var area = ol.Sphere.getArea(geom);
            var output;
            if (area > 10000) {
                output = (Math.round(area / 1000000 * 100) / 100) +
                    ' ' + 'km<sup>2</sup>';
            } else {
                output = (Math.round(area * 100) / 100) +
                    ' ' + 'm<sup>2</sup>';
            }

            document.getElementById('text').innerHTML = output;
        }


        if (geom instanceof ol.geom.LineString || geom instanceof ol.geom.MultiLineString) {
            var length = ol.Sphere.getLength(geom);
            var output;
            if (length > 100) {
                output = (Math.round(length / 1000 * 100) / 100) +
                    ' ' + 'km';
            } else {
                output = (Math.round(length * 100) / 100) +
                    ' ' + 'm';
            }
            document.getElementById('text').innerHTML = output;
        }


    }

    function diling() {
        thisfeature.set("size", 1);
        thisfeature.set("text", "");
    }

    function dell() {
        map.removeLayer(vectorLayer)
    }

</script>
</body>
</html>